﻿using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;

namespace SHDM.Web
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            if (ConfigurationManager.AppSettings.AllKeys.Contains("cors:allowedMethods") &&
                 ConfigurationManager.AppSettings.AllKeys.Contains("cors:allowedOrigin") &&
                 ConfigurationManager.AppSettings.AllKeys.Contains("cors:allowedHeaders"))
            {
                var allowedMethods = ConfigurationManager.AppSettings["cors:allowedMethods"];
                var allowedOrigin = ConfigurationManager.AppSettings["cors:allowedOrigin"];
                var allowedHeaders = ConfigurationManager.AppSettings["cors:allowedHeaders"];
                config.EnableCors(new EnableCorsAttribute(allowedOrigin, allowedHeaders, allowedMethods));
            }

            config.Filters.Add(new Infrastructure.AuthenticatorAttribute());
            config.Filters.Add(new Infrastructure.ExceptionFilter());

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // 干掉XML序列化器
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            // 解决json序列化时的循环引用问题
            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            config.Formatters.JsonFormatter.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            // 对 JSON 数据使用混合大小写。驼峰式,但是是javascript 首字母小写形式.
            //config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new  CamelCasePropertyNamesContractResolver();
            // 对 JSON 数据使用混合大小写。跟属性名同样的大小.输出
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();
        }
    }
}
